import { createRouter, createWebHistory } from 'vue-router'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      redirect: '/home',
    },
    {
      path: '/login',
      component: () => import('../views/login.vue'),
    },
    {
      path: '/home',
      component: () => import('../views/home/index.vue'),
    },
    {
      path: '/:path(.*)*',
      component: () => import('@/views/notFound.vue'),
    },
  ],
})
router.beforeEach((to, from, next) => {
  console.log('设置全局守卫')
  // 判断有没有登录
  // 如果没有登录,就只能去登录界面
  if (!localStorage.getItem('token') && to.path != '/login') {
    return next({ path: '/login' })
  }
  // 如果已经登录过，还要去登录界面，及直接回到来的地方
  if (localStorage.getItem('token') && to.path == '/login') {
    alert('您已登录')
    return next('/home')
  }
  // 不设置next()会变成空白
  next()
})
export default router
